import requests
import json
import datetime
import queue
import time
import threading
from get_config import *

"""
流程：
    1.机器检测完成后上传条码和检测结果（message_update）返回值为1

软件启动时同时启动class MesServers用于获取token

上传过程中会自动保存日志在目录log下

url目前均为测试环境实际使用预计将更改

剩下参数根据客户需求更改
"""


def uctime():
    gmt_format = '%a,%d %b %Y %H:%M:%S GMT+0800'
    # gmtformat = '%Y%b%d-%H%M%S'
    time_uc = datetime.datetime.utcnow().strftime(gmt_format)
    # ti = datetime.now().strftime(gmtformat)
    return time_uc


def get_token(ss):
    # url = "http://10.177.8.193:9989/API/Auth/SignIn"  # 生产用
    # url = 'http://127.0.0.1:5000/api'   #测试用
    url = config['mes_url']
    userid = config['mes_user']
    pwdid = config['mes_password']
    payload = json.dumps({
        "user": userid,
        "pwd": pwdid
    })
    headers = {
        'Content-Type': 'application/json'
    }
    try:
        response = requests.request("POST", url, headers=headers, data=payload)
        data = json.loads(response.text)
        data = data['Data']['Token']
        data = 'Bearer ' + data
        ss.zz = data
        massagess = 'Token update success'
        logger.info(massagess)
        # log.info(massagess)

    except Exception as e:
        massagess = f'Token get err:{e}'
        ss.zz = 0
        logger.error(massagess)
        time.sleep(5)
        # log.info(massagess)
    # print(data)
    return 0


def mes_token_get(ss):
    while True:
        get_token(ss)
        if ss.zz == 0:
            get_token(ss)
        else:
            time.sleep(900)


def timenow():
    # datenow = datetime.datetime.today()
    datenow = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    return datenow


class MesServers:
    def __init__(self) -> None:
        self.zz = None
        self.si = queue.Queue()
        self.si.put(0)
        self.thread_work = None
        self.client_sockets = []
        self.thread_working = False
        self.start()

    def __del__(self):
        self.stop()

    def start(self):
        if self.thread_work is None:
            self.thread_working = True
            self.thread_work = threading.Thread(target=mes_token_get, args=(self,))
            self.thread_work.start()

    def wuhan_message_update(self, pro, end):
        # pro为条码,end为结果(0为成功，1为失败)
        try:
            midea_token = self.zz
            device = config['scadaid']
            detectionline = config['chanxian']
            workcenter = config['workcenter']
            stepname = config['checkname']
            org = config['org']
            if end:
                end = "FAIL"
                end2 = "NG"
                end3 = "DefaultCode"
            else:
                end = "PASS"
                end2 = "OK"
                end3 = ""
            url = config['mes_upurl']  # 测试
            payload = json.dumps({
                "INV_ORG_ID": org,  # 二期300052  /一期200123
                "BARCODE": pro,
                "DATETIME_ACQUISITION": timenow(),
                "DEVICE_CODE": device,
                "totalSteps": "1",
                "TEST_STATUS": end,
                "detectionLine": detectionline,
                "WORKCENTER_CODE": workcenter,
                "user": "AI_CHECK",
                "totalErrCode": end3,
                "detail": [
                    {
                        "stepNum": "1",
                        "stepName": stepname,
                        "stepResult": end,
                        "Args": [
                            {
                                "comment": stepname,
                                "value": end2,
                                "result": end,
                                "test_conditions": ""
                            }
                        ]
                    }
                ]
            })

            headers = {
                'Authorization': midea_token,
                'Content-Type': 'application/json'
            }
            datass = f"message_update:{payload}"
            logger.info(datass)
            # log.info(datass)
            try:
                response = requests.request("POST", url, headers=headers, data=payload, timeout=20)
                data = json.loads(response.text)
                logger.info(data)
            except Exception as e:
                datass = f"message_update{pro, end, e}"
                logger.error(datass)
                # log.error(datass)
        except Exception as e:
            datass = f"message_update_err{e}"
            logger.error(datass)

        # print(data)
        return 1

    def stop(self):
        if self.thread_work is not None:
            self.thread_working = False
            self.thread_work.join()
            self.thread_work = None
        self.si.put(-1)

    def close(self):
        self.stop()

    def close_s(self, s):
        print('close_s:', s)
        self.close()

        return 0


if __name__ == "__main__":
    print(timenow())
    # mes_token_get()
    # http = MesServers()
    # # time.sleep(5)
    # http.wuhan_message_update('12345456','ok')
